<template>
  <div class="authority" v-loading="loading">
    <div class="inner">
      <div class="operate">
        <div class="searchphone">
          <div>手机号</div>
          <el-input v-model="search" placeholder="请输入手机号" />
          <el-button type="primary" @click="searchPhoneAuthority">查询</el-button>
        </div>
        <div>
          <el-button @click="flashReloadPhoneAuthority">刷新</el-button>
          <el-button type="primary" @click="showPhoneAuthority">添加</el-button>
        </div>
      </div>
      <div class="information">
        <div class="box" v-for="item in authorities" >
          <div @click="copyToClipboard(item)">
            <div>{{ item.loginphone }}</div>
            <div>{{ item.sharecode }}</div>
          </div>
          <svg-icon class="close" name="close" size="13" @click="deleteAuthority(item.loginphone)"></svg-icon>
        </div>
      </div>
      <el-dialog v-model="showDialog" title="授权号码" width="600px" center>
        <el-form ref="refAuthorityForm" :model="authorityForm"  :rules="verifyRules">
          <el-form-item prop="username" label="用户名">
            <el-input
                ref="username"
                v-model="authorityForm.username"
                placeholder="请输入用户名"
                name="loginphone"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="nickname" label="中文名">
            <el-input
                ref="nickname"
                v-model="authorityForm.nickname"
                placeholder="请输入中文名"
                name="loginphone"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="loginphone" label="手机号">
            <el-input
                ref="loginphone"
                v-model="authorityForm.loginphone"
                placeholder="请输入手机号码"
                name="loginphone"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="sharecode" label="授权码">
            <el-input
                ref="sharecode"
                v-model="authorityForm.sharecode"
                placeholder="请输入有效授权码"
                name="sharecode"
                type="text"
                auto-complete="on">
              <template #append>
                <el-button type="primary" @click="createSharecode">生成授权码</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%;margin-top:20px;"
                     @click.prevent="handleAuthority(refAuthorityForm)">添加授权</el-button>
        </el-form>
      </el-dialog>
      <svg-icon class="astro left" name="color-scheme-left"></svg-icon>
      <svg-icon class="astro right" name="color-scheme-right"></svg-icon>
      <el-link :underline="false" v-show="showLoadMore" v-on:click="reloadPhoneAuthority"><h3>{{ textBeginLoading }}</h3></el-link>
    </div>
  </div>
</template>

<script lang="ts">
import {onMounted, reactive, ref} from "vue";
import {IAuthority} from "@/iwb/IConfig";
import {FormInstance, FormRules} from "element-plus";
import {validContactPhone} from "@/utils/validate";
import SvgIcon from "@/icons/index.vue";
import {Md5Utils} from "@/utils/Md5Utils";
import useClipboard from 'vue-clipboard3'
import {DialogUtils} from "@/utils/DialogUtils";
import {useConfigStore} from "@/store/config";
import {addPhoneAuthority} from "@/api/config";

export default {
  name: "Authority",
  components: {SvgIcon},
  setup() {
    const search = ref('');
    const loading = ref(false);
    const showDialog = ref(false);
    const authorityForm = ref({} as IAuthority);
    const refAuthorityForm = ref<FormInstance>();
    const validateContact = (rule: any, value: string, callback: any) => {
      if (!validContactPhone(value) || value.length !== 11) {
        callback(new Error('请输入正确的手机号'))
      }  else {
        callback();
      }
    };
    const validateUsername = (rule: any, value: string, callback: any) => {
      const zg = /^\w+$/;
      if (zg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入数字和字母组合的用户名'));
      }
    }
    const verifyRules = reactive<FormRules>({
      username: [{required: true, trigger: 'blur', validator: validateUsername}],
      nickname: [{required: true, trigger: 'blur', message: '请输入中文名'}],
      loginphone: [{required: true, trigger: 'blur', validator: validateContact}],
      sharecode: [{required: true, trigger: 'blur', message: '请输入有效授权码'}]
    })
    const createSharecode = () => {
      const loginphone = authorityForm.value.loginphone;
      if (!loginphone) {
        DialogUtils.showWarningBox("温馨提示", "请输入手机号，再创建授权码");
        return;
      }
      if (!validContactPhone(loginphone) || loginphone.length !== 11) {
        DialogUtils.showWarningBox("温馨提示", "请输入正确的手机号");
        return;
      }
      const sharecode = loginphone + Date.now();
      authorityForm.value.sharecode = Md5Utils.b64MD5(sharecode).toUpperCase();
    }
    const authorities = ref([] as Array<IAuthority>);
    const {toClipboard} = useClipboard();
    const copyToClipboard = async (item: IAuthority) => {
      const text = item.loginphone + '\n' + item.sharecode;
      try {
        await toClipboard(text);
        DialogUtils.showWarningBox("剪切板", "已经复制到剪切板");
      } catch (e) {
        console.error(e);
        DialogUtils.showErrorBox("提示", "复制到剪切板失败");
      }
    }
    const pageIndex = ref(0);
    const pageSize = ref(20);
    const totalCount = ref(0);
    const needFlashData = ref(true);
    const textBeginLoading = ref('加载更多');
    const showLoadMore = ref(false);
    const mergeDelNumber = ref(0);
    const needReloadMore = () => {
      if(textBeginLoading.value === '重新加载') {
        pageIndex.value = 0;
        authorities.value = [];
        textBeginLoading.value = '加载更多';
      }
    }
    /**
     * 加载已经添加的手机授权码
     */
    const configStore = useConfigStore();
    const reloadPhoneAuthority = () => {
      needReloadMore();
      const index = pageIndex.value;
      const size = pageSize.value;
      if (totalCount.value > index * size || pageIndex.value ===0) {
        configStore.getPhoneAuthority(pageIndex.value + 1, pageSize.value).then((res: any) => {
          const { data } = res;
          totalCount.value = data.total;
          merge2DeleteData();
          authorities.value.push(...data.authorities);
          pageIndex.value += 1;
          showLoadMore.value = totalCount.value > pageIndex.value * size;
        })
      } else {
        showLoadMore.value = false;
      }
    }



    /**
     * mergeDelNumber由于手动添加数据
     * 导致数据库后台重新查询的时候，发生
     * 了重复项目，而重复项目在末尾，所以
     * 添加几个就删除几个
     */
    const merge2DeleteData = () => {
      const num = mergeDelNumber.value;
      if(num > 0) {
        const length = authorities.value.length;
        authorities.value.splice(length - num, num);
        mergeDelNumber.value = 0;
      }
    }

    const handleAuthority = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.validate((valid: boolean, fields) => {
        if (valid) {
          loading.value = true;
          configStore.addPhoneAuthority(authorityForm.value).then((res) => {
            mergeDelNumber.value += 1;
            authorities.value.unshift(authorityForm.value);
            loading.value = false;
            showDialog.value = false;
          }).catch(error => {
            loading.value = false;
            console.error(error);
          })
        } else {
          loading.value = false
          console.log('error submit!!', fields);
        }
      });
    }

    const deleteAuthority = (loginphone: string) => {
      return new Promise((resolve, reject) => {
        DialogUtils.showMessageBox("温馨提示", "是否确认删除授权？？", {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          loading.value = true;
          console.log('then');
          configStore.deletePhoneAuthority(loginphone).then((res: any) => {
            let index = authorities.value.findIndex(item => item.loginphone === loginphone);
            authorities.value.splice(index, 1);
            loading.value = false;
          }).catch(err=>{
            console.error(err)
            loading.value = false;
          })
        }).catch((err)=>{
          console.error(err)
          loading.value = false;
        })
      })
    }

    const flashReloadPhoneAuthority = () => {
      mergeDelNumber.value = 0;
      authorities.value = [];
      pageIndex.value = 0;
      totalCount.value = 0;
      reloadPhoneAuthority();
    }
    const showPhoneAuthority = () => {
      authorityForm.value.loginphone = "";
      authorityForm.value.sharecode = "";
      showDialog.value = true;
    }

    const searchPhoneAuthority = () => {
      showLoadMore.value = false;
      authorities.value = [];
      configStore.searchPhoneAuthority(search.value).then((res: any) => {
        const { data } = res;
        totalCount.value = data.total;
        merge2DeleteData();
        authorities.value.push(...data.authorities);
      });
    }


    onMounted(() => {
      mergeDelNumber.value = 0;
      authorities.value = [];
      reloadPhoneAuthority();
    })

    return {
      search,
      loading,
      showDialog,
      authorityForm,
      refAuthorityForm,
      verifyRules,
      authorities,
      textBeginLoading,
      showLoadMore,
      createSharecode,
      copyToClipboard,
      handleAuthority,
      deleteAuthority,
      reloadPhoneAuthority,
      flashReloadPhoneAuthority,
      showPhoneAuthority,
      searchPhoneAuthority
    }
  }
}
</script>

<style scoped lang="scss">
@import "src/styles/variable";
  .authority {
    position: relative;
    margin: 10px;
    //background-color: $color-sub-background-base;
    background-image: linear-gradient(to right top, #38438b, #944b94, #d75a88, #ff7e71, #ffb25f, #ffeb68);
    height: calc(100% - 20px);
    box-sizing: border-box;
    border-radius: 5px;
    .inner {
      position: relative;
      background-color: rgba(255,255,255,0.5);
      height: 100%;
      box-sizing: border-box;
      border-radius: 5px;
      text-align: center;
    }
    .astro {
      width: 40% !important;
      height: 40% !important;
    }
    .left {
      position: absolute;
      bottom: 20px;
      left: 0;
    }
    .right {
      position: absolute;
      bottom: 20px;
      right: 0;
    }
    .operate {
      display: flex;
      justify-content: space-between;
      padding: 10px 24px;
      align-items: center;
      border-bottom: 1px solid $color-border-base;

      .searchphone {
        display: flex;
        align-items: center;
        color: $color-text-label-base;
        gap: 10px;
      }

      .el-input {
        width: 200px;

      }
    }
    .information {
      padding: 10px 24px;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      align-content: flex-start;
      //justify-content: space-between;
      .box {
        width: 300px;
        position: relative;
        padding: 12px 20px;
        background-color: rgba(255,255,255,0.5);
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        border: 0;
        backdrop-filter: blur(5px);
        .close {
          position: fixed;
          right: 0;
          top: 0;
          margin: 5px;
          z-index: 10;
        }
      }
      .box:hover {
        -webkit-transform: scale(1.06);
        -o-transform: scale(1.06);
        transform: scale(1.06);
        -ms-transform: scale(1.06);
        cursor: pointer;
      }
    }
    .information:after {
      //content: '';
      //flex: auto;
    }
  }
</style>